// 连线颜色
var DEDAULT_LINE_COLOR = "gray";
var ALL_COMM_SUCC_LINE_COLOR = "#00A959"; // 浅红
var PART_COMM_SUCC_LINE_COLOR = "#FF56A6"; // 浅绿
var NETWORK_SUCC_LINE_COLOR = "#007D7A"

// 文本颜色
var LINE_TEXT_COLOR = "gray";
// var TERMINAL_TEXT_COLOR = "#3381D1";
var TERMINAL_TEXT_COLOR = "red";
var IGROUP_TEXT_COLOR = "red";

// 串口通信超时时间
var SERIAL_PORT_TIME_OUT = 60;

// 当前默认指示器组
var DEFAULT_IGROUP_ID;

var svgns = "http://www.w3.org/2000/svg";

// 终端的宽度和高度
var TERMINAL_WIDTH = 50;
var TERMINAL_HEIGHT = 60;

// circle RADIUS
var RADIUS = 30;

// 指示器/终端相邻系数
var NEAR_FACTOR = 5;

// 当前操作的元素
var workElem;

// 坐标点属性
function Point(x, y) {
	this.x = x;
	this.y = y;
}

/**
 * 指示器组和终端坐标修改
 * 
 * @param {}
 *            obj
 * @param {}
 *            x
 * @param {}
 *            y
 */
function modifyCoord(obj, x, y) {

	var i = 0;
	var noObj = true;
	var opi = getCPoint(obj);
	var iGroups = $("g[tags]");
	for (i = 0; i < iGroups.length; i++) {

		if (obj == iGroups[i]) {
			noObj = false;
			break;
		}
	}

	if (!noObj) {
		// 
		var cx = Number(opi.x) + Number(x);
		var cy = Number(opi.y) + Number(y);

		iGroups[i].setAttribute("point", cx + "," + cy);

	}
}

/**
 * 在中心位置创建终端
 */
var createTerminal = function(terminalAddr) {

	var group;
	var terminal = $("#Terminal", WORK_SVG);
	if (0 == terminal.length) {

		var x = $(window).width() / 2;
		var y = 90;

		group = document.createElementNS(svgns, 'g');
		group.setAttribute("transform", "translate("
						+ Number(x - TERMINAL_WIDTH / 2) + ","
						+ Number(y - TERMINAL_HEIGHT / 2) + ")");
		group.setAttribute("height", TERMINAL_HEIGHT);
		group.setAttribute("width", TERMINAL_WIDTH);
		group.setAttribute("point", x + "," + y);
		group.setAttribute("tags", "0");
		group.id = "Terminal";

		var text = document.createElementNS(svgns, 'text');
		text.setAttribute("transform", "translate(" + (TERMINAL_WIDTH / 2 - 2)
						+ ",-5)");
		text.setAttribute("font-size", 14);
		text.setAttribute("fill", TERMINAL_TEXT_COLOR);
		text.setAttribute("text-anchor", "middle");
		text.textContent = terminalAddr.toUpperCase();
		text.id = "TerminalAddr";
		group.appendChild(text);

		var svg_img = document.createElementNS(svgns, "image");
		svg_img.href.baseVal = "../../image/t1800d.jpg";
		svg_img.setAttribute("transform", "translate(0,0)");
		svg_img.setAttribute("height", TERMINAL_HEIGHT);
		svg_img.setAttribute("width", TERMINAL_WIDTH);

		group.appendChild(svg_img);
		WORK_SVG.appendChild(group);
	} else {
		group = document.getElementById("Terminal");
		var text = $("#TerminalAddr", WORK_SVG)[0];
		text.textContent = terminalAddr.toUpperCase();
	}

	$(group).unbind("tap").bind("tap", function(event) {
				var group = this;
				if (2 == workMode) {
					var opi = getCPoint(this);

					var str = "选中设备: 配网终端 [ " + $("#currterminal").val() + " ]";
					showMsg(str);
				}

				return false;
			});

	/**
	 * 终端长按绑定事件，显示档案操作对话框（修改）
	 */
	$(group).unbind("taphold").bind("taphold", function(event) {

				if (2 == workMode) {
					return;
				}
				currObj = this;
				clearSelectedStatus();

				var popup = $("#terminalpopupmenu");
				if (0 == workMode) {

					$("a", popup).show();
					// 隐藏调试相关按钮
					$("#terminalverbtn", popup).css({
								"display" : "none"
							});
					$("#qsterminaladdrbtn", popup).css({
								"display" : "none"
							});
					$("#qscommparamsbtn", popup).css({
								"display" : "none"
							});
					$("#qscommstatusbtn", popup).css({
								"display" : "none"
							});
					$("#terminalresetbtn", popup).css({
								"display" : "none"
							});
				} else if (1 == workMode) {
					$("a", popup).show();
					// 隐藏指修改按钮
					$("#modifybtn", popup).css({
								"display" : "none"
							});
				}

				// 对话框中的按钮都显示
				popup.popup("option", "positionTo", $(this));
				popup.trigger("create");
				popup.popup("open");

				$("#terminalmenugroup").controlgroup("refresh");

				return false;
			});

	$(group).pep({
		// debug : true,
		SVGtype : true,
		constrainTo : 'window',
		drag : function(ev, obj) {
			if (0 != workMode) {
				return false;
			}

			var x = ev.pep.x;
			var y = ev.pep.y - HEADER_HEIGHT;
			var point = new Point(x, y);
			var space = Math.pow(Math.pow((x - dragPreCoord.x), 2)
							+ Math.pow((y - dragPreCoord.y), 2), 0.5);

			if (space > (0.5 * RADIUS)) {// 步长
				dragPreCoord = point;
				repaintLine(obj);
			}
		},
		stop : function(ev, obj) {
			if (0 != workMode) {
				return false;
			}

			repaintLine(obj);
		}
	});
};

/**
 * 安装模式下点击，安装指示器
 */
var installIndicator = function(evt) {

	var obj = evt.target.parentNode;
	var box = obj.getBoundingClientRect();

	var x = evt.pageX;
	var y = evt.pageY - box.top - this.scrollY;

	var point = new Point(x, y);
	createIGroup(point, evt);

	return false;
};

/**
 * 获取中心坐标点
 * 
 * @param {}
 *            elem
 * @return {}
 */
var getCPoint = function(elem) {

	var pstr = elem.getAttribute("point").split(",");
	var cx = parseFloat(pstr[0]);
	var cy = parseFloat(pstr[1]);

	var point = new Point(cx, cy);
	return point;
}

// 上一节点和下一结点，表现从……到的关系
var fromNode = null;
var toNode = null;
/**
 * 取消对选中的指示器和终端状态
 */
var clearSelectedStatus = function(event) {
	var iGroups = $("g[tags]");
	for (var i = 0; i < iGroups.length; i++) {
		var group = iGroups[i];
		if (group.getAttribute("tags") != 0) {

			changeSelectedStatus(group, 0);

			// 取消上一节点/下一节点
			fromNode = null;
			toNode = null;
		}
	}
};

/**
 * 改变选中状态
 * 
 * @param {}
 *            obj
 * @param {}
 *            tags 1修改为选中；0修改为取消
 */
var changeSelectedStatus = function(obj, tags) {

	var currTags = obj.getAttribute("tags");
	if (currTags == tags) {
		return;
	}

	obj.setAttribute("tags", tags);

	var cir = $("circle", obj);
	if (cir.length > 0) {
		var x = Number(cir[0].getAttribute("cx"));
		var y = Number(cir[0].getAttribute("cy"));

		if (1 == tags) {
			cir[0].setAttribute("cx", x + 4); // 外凸显
			cir[0].setAttribute("cy", y + 3);
			cir[0].setAttribute("style", "fill:url(#selectedgradient)"); // 增加样式

		} else if (0 == tags) {
			cir[0].setAttribute("cx", x - 4); // 取消凸显
			cir[0].setAttribute("cy", y - 3);
			cir[0].setAttribute("style", "fill:''");
		}
	}
};

/**
 * svg面板上滑动选择指示器
 */
var selectIgroupElem = function(point, event) {

	var objs = $("g[tags]");

	for (var i = 0; i < objs.length; i++) {

		var group = objs[i];
		var tag = group.getAttribute("tags");
		// 判断是否已经选择改指示器组
		if (tag == "0") {

			var dpoint = getCPoint(group);
			var space = Math.pow(Math.pow((point.x - dpoint.x), 2)
							+ Math.pow((point.y - dpoint.y), 2), 0.5);

			// 判断距离
			if (space < RADIUS) {
				changeSelectedStatus(group, 1);

				if (fromNode == null) {
					fromNode = group;
					RELAY_NODES.push(fromNode);
				}

				toNode = group;

				if (fromNode != toNode) {
					RELAY_NODES.push(toNode);
					makeLine(fromNode, toNode);
					fromNode = toNode;
				}

				IG_TERM_SELECTED_ARR.push(group.getAttribute("id"));
				// var str = "已选择指示器组：" + group.getAttribute("id");
				// showMsg(str);
			}
		}

	}
};

/**
 * 生成指示器组
 * 
 * @param {}
 *            point
 * @param {}
 *            event
 * @return {Boolean}
 */
var createIGroup = function(point, event) {

	// 判断点击位置附近是否有其他的指示器/终端
	var isValid = isValidCoord(point);
	if (!isValid) {
		var str = "附近存在其他指示器/终端!";
		showMsg(str);
		return false;
	}

	var x = parseFloat(point.x);
	var y = parseFloat(point.y);

	try {
		var lineId = $("#tlineid").val();
		window.indicatorjsi.getMaxGroupNo(lineId, x, y);
	} catch (e) {
	}
}

/**
 * 准备添加指示器组准备的回调函数
 * 
 * @param {}
 *            data
 */
var readyIgroupCallback = function(data) {

	var x = Number(data.x);
	var y = Number(data.y);
	var point = new Point(x, y);
	var groupNo = Number(data.maxGroupNo) + 1;

	// 创建一个新的节点
	var group = document.createElementNS(svgns, 'g');
	group.setAttribute("etype", "indicator");
	group.setAttribute("tags", "0");
	group.setAttribute("groupno", groupNo + "");
	group.setAttribute("point", x + "," + y);
	group.setAttribute("height", 2 * RADIUS);
	group.setAttribute("width", 2 * RADIUS);
	group.setAttribute("transform", "translate(" + Number(x - RADIUS) + ","
					+ Number(y - RADIUS) + ")");
	group.id = "G" + groupNo;

	// 预先设置一个区域作为指示器安装位置，若不添加指示器则会撤销
	var circle = document.createElementNS(svgns, "circle");
	circle.setAttribute("transform", "translate(" + RADIUS + ", " + RADIUS
					+ ")");
	// circle.cx.baseVal.value = point.x;
	// circle.cy.baseVal.value = point.y;
	circle.r.baseVal.value = RADIUS;
	group.appendChild(circle);

	WORK_SVG.appendChild(group);
	workElem = group;

	// 指示器添加对话框预设值
	$("#igroupoperspan", $("#igrouppopup")).html("添加");
	$(".ui-btn-text", $("#igroupeditbtn")).html("添加");
	$("#groupno", $("#igrouppopup")).val(groupNo);
	$("#opermode", $("#igrouppopup")).val("add");

	// 清空表单
	$("#indicatorid_a", $("#igrouppopup")).val("");
	$("#indicatorid_b", $("#igrouppopup")).val("");
	$("#indicatorid_c", $("#igrouppopup")).val("");
	$("#indicatoraddr_a", $("#igrouppopup")).val("");
	$("#indicatoraddr_b", $("#igrouppopup")).val("");
	$("#indicatoraddr_c", $("#igrouppopup")).val("");
	$("#location", $("#igrouppopup")).val("");
	$(".tipcontentspan", $("#igrouppopup")).html("");

	$("#indicatoraddr_a", $("#igrouppopup")).focus();

	// 指示器组编辑（新增修改）按钮绑定事件
	$("#igroupeditbtn", $("#igrouppopup")).unbind().bind("click", editIgroup);
	// 指示器组取消按钮绑定事件
	$("#igroupcancelbtn", $("#igrouppopup")).unbind().bind("tap",
			cancelEditIgroup);

	// 显示指示器添加表单
	$("#igrouppopup").trigger("create");
	$("#igrouppopup").popup("open");

	/**
	 * 指示器组长按live绑定（当前和未来的指示器组都具有的事件）
	 */
	$(group).unbind("taphold").bind("taphold", function(event) {

				if (2 == workMode) {
					return;
				} else if (0 == workMode) {
					$("a", $("#igrouppopupmenu")).show();
					// 隐藏指示器组中的实时电流按钮、休眠时间按钮、通信目的指示器按钮
					$("#rtcurrentbtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#sleeptimebtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#targetindicatorbtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#indicatorverbtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#fliptestbtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#rtefbtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#commaddrresetbtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
				} else if (1 == workMode) {
					$("a", $("#igrouppopupmenu")).show();
					// 隐藏指示器组中的修改按钮、删除按钮
					$("#modifybtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
					$("#removebtn", $("#igrouppopupmenu")).css({
								"display" : "none"
							});
				}

				workElem = this;
				clearSelectedStatus();

				/**
				 * $("a", $("#popupmenu")).show(); // 隐藏新增按钮，弹出修改和删除按钮 $($("a",
				 * $("#popupmenu"))[0]).css({ "display" : "none" });
				 */
				showIGroupOperPopup(this);

				changeSelectedStatus(this, 1);
				return false;
			});

	// 对当前指示器组绑定点击事件：安装模式下加载指示器组信息；查询模式下消息框的形式显示指示器组信息
	$(group).unbind("tap").bind("tap", function(event) {

				var group = this;
				currObj = this;
				workElem = this;

				if (2 == workMode) {
					var id = group.id;
					var tip = "选中设备: 指示器组 [ " + id + "组 ]<br/>";

					var children = group.childNodes;

					var iid = children[1].id;
					if (iid) {
						tip += "A相地址: " + iid.substring(9) + "<br/>";
					}

					iid = children[2].id;
					if (iid) {
						tip += "B相地址: " + iid.substring(9) + "<br/>";
					}

					iid = children[3].id;
					if (iid) {
						tip += "C相地址: " + iid.substring(9) + "<br/>";
					}

					showMsg(tip, 6000);
				}

				return false;
			});

	/**
	 * 对打开的SVG的指示器组绑定拖拽事件，重绘之间的连线
	 */
	$(group).pep({
		SVGtype : true,
		constrainTo : 'window',
		drag : function(ev, obj) {
			if (0 != workMode) {
				return false;
			}

			var x = ev.pep.x;
			var y = ev.pep.y - HEADER_HEIGHT;
			var point = new Point(x, y);
			var space = Math.pow(Math.pow((x - dragPreCoord.x), 2)
							+ Math.pow((y - dragPreCoord.y), 2), 0.5);

			if (space > (0.5 * RADIUS)) {// 步长
				dragPreCoord = point;
				repaintLine(obj);
			}
		},
		stop : function(ev, obj) {
			if (0 != workMode) {
				return false;
			}

			repaintLine(obj);
		}
	});
};

/**
 * 删除指示器组的回调方法
 * 
 * @param {}
 *            data
 */
var removeIGroupCallback = function(data) {

	// 关闭删除确认对话框
	$("#removeconfirmpopup").popup("close");

	var groupNo = data.groupno;
	var group = document.getElementById("G" + groupNo)

	var lines = $("g[line]");
	for (var i = lines.length - 1; i >= 0; i--) {
		var sNode = document.getElementById(lines[i].getAttribute("sid"));
		var eNode = document.getElementById(lines[i].getAttribute("eid"));

		if (sNode == group || eNode == group) {
			WORK_SVG.removeChild(lines[i]);
			if (fromNode == group) {
				fromNode = null;
			}

			if (toNode == group) {
				toNode = null;
			}
		}

	}
	WORK_SVG.removeChild(group);
};

/**
 * 加载指示器组的回调函数
 * 
 * @param {}
 *            data
 */
var queryIGroupCallback = function(data) {

	// 指示器添加对话框预设值
	$("#igroupoperspan", $("#igrouppopup")).html("修改");
	$(".ui-btn-text", $("#igroupeditbtn")).html("修改");

	// 清空提示语
	$(".tipcontentspan", $("#igrouppopup")).html("");

	// 填充返回值
	$("#opermode", $("#igrouppopup")).val("modify");
	$("#groupno", $("#igrouppopup")).val(data.groupno);
	$("#indicatorid_a", $("#igrouppopup")).val(data.indicatorIdA);
	$("#indicatorid_b", $("#igrouppopup")).val(data.indicatorIdB);
	$("#indicatorid_c", $("#igrouppopup")).val(data.indicatorIdC);
	$("#indicatoraddr_a", $("#igrouppopup")).val(data.indicatorAddrA);
	$("#indicatoraddr_b", $("#igrouppopup")).val(data.indicatorAddrB);
	$("#indicatoraddr_c", $("#igrouppopup")).val(data.indicatorAddrC);
	$("#location", $("#igrouppopup")).val(data.location);

	// 指示器组编辑（新增修改）按钮绑定事件
	$("#igroupeditbtn", $("#igrouppopup")).unbind().bind("click", editIgroup);
	// 指示器组取消按钮绑定事件
	$("#igroupcancelbtn", $("#igrouppopup")).unbind().bind("tap",
			cancelEditIgroup);

	// 显示指示器编辑表单
	$("#triggerigrouppopup").click();
	// $("#igrouppopup").trigger("create");
	// $("#igrouppopup").popup("open");

	return false;
};

/**
 * 修改指示器组信息
 * 
 * @return {Boolean}
 */
var editIgroup = function() {

	var lineId = $("#tlineid").val();
	var terminalId = $("#terminalid").val();
	var groupNo = $("#groupno", $("#igrouppopup")).val();
	var location = $("#location", $("#igrouppopup")).val();
	var indicatorIdA = $("#indicatorid_a", $("#igrouppopup")).val();
	var indicatorIdB = $("#indicatorid_b", $("#igrouppopup")).val();
	var indicatorIdC = $("#indicatorid_c", $("#igrouppopup")).val();
	var indicatorAddrA = $("#indicatoraddr_a", $("#igrouppopup")).val();
	var indicatorAddrB = $("#indicatoraddr_b", $("#igrouppopup")).val();
	var indicatorAddrC = $("#indicatoraddr_c", $("#igrouppopup")).val();
	var operMode = $("#opermode", $("#igrouppopup")).val();
	var location = $("#location", $("#igrouppopup")).val();

	var msg = "";
	if (0 == indicatorAddrA.trim().length && 0 == indicatorAddrB.trim().length
			&& 0 == indicatorAddrC.trim().length) {
		msg = "A、B、C相指示器地址不能都为空!";
		$(".tipcontentspan", $("#igrouppopup")).html(msg);
		$("#indicatoraddr_a", $("#igrouppopup")).focus();
		return false;
	}

	if (0 < indicatorAddrA.trim().length && 6 != indicatorAddrA.trim().length) {
		msg = "A相指示器地址的长度错误, 长度为6个字符!";
		$(".tipcontentspan", $("#igrouppopup")).html(msg);
		$("#indicatoraddr_a", $("#igrouppopup")).focus();
		return false;
	}

	if (0 < indicatorAddrB.trim().length && 6 != indicatorAddrB.trim().length) {
		msg = "B相指示器地址的长度错误, 长度为6个字符!";
		$(".tipcontentspan", $("#igrouppopup")).html(msg);
		$("#indicatoraddr_b", $("#igrouppopup")).focus();
		return false;
	}

	if (0 < indicatorAddrC.trim().length && 6 != indicatorAddrC.trim().length) {
		msg = "C相指示器地址的长度错误, 长度为6个字符!";
		$(".tipcontentspan", $("#igrouppopup")).html(msg);
		$("#indicatoraddr_c", $("#igrouppopup")).focus();
		return false;
	}

	$("#indicatoraddr_a", $("#igrouppopup")).val(indicatorAddrA.toUpperCase());
	$("#indicatoraddr_b", $("#igrouppopup")).val(indicatorAddrB.toUpperCase());
	$("#indicatoraddr_c", $("#igrouppopup")).val(indicatorAddrC.toUpperCase());

	DEFAULT_IGROUP_ID = "G" + groupNo;
	try {
		var params = "{";
		params += "'lineId': '" + lineId + "',";
		params += "'terminalId': '" + terminalId + "',";
		params += "'operMode': '" + operMode + "',";
		params += "'indicatorAddrA': '" + indicatorAddrA + "',";
		params += "'indicatorAddrB': '" + indicatorAddrB + "',";
		params += "'indicatorAddrC': '" + indicatorAddrC + "',";
		params += "'location': '" + location + "',";
		params += "'groupNo': '" + groupNo + "'";

		if ('add' == operMode) {
			params += "}";
			window.indicatorjsi.addIGroup(params);
		} else if ('modify' == operMode) {
			params += ",";
			params += "'indicatorIdA': '" + indicatorIdA + "',";
			params += "'indicatorIdB': '" + indicatorIdB + "',";
			params += "'indicatorIdC': '" + indicatorIdC + "'";
			params += "}";
			window.indicatorjsi.modifyIGroup(params);
		}
	} catch (e) {
	}

	return false;
};

/**
 * 添加/修改指示器组成功的回调函数
 * 
 * @param {}
 *            data
 */
var igroupAMSuccuessCallback = function(data) {

	var success = data.success;
	if (!success) {
		var msg = "";
		var flag = data.flag;
		if (1 == flag) {
			msg = "指示器地址已存在[ " + data.repeatIAddrs + " ], 不能重复添加!";
		} else {
			msg = "操作异常!";
		}

		$(".tipcontentspan", $("#igrouppopup")).html(msg);
		return;
	}

	var indicatorAddrA = $("#indicatoraddr_a", $("#igrouppopup")).val();
	var indicatorAddrB = $("#indicatoraddr_b", $("#igrouppopup")).val();
	var indicatorAddrC = $("#indicatoraddr_c", $("#igrouppopup")).val();

	// 当前html 指示器组对象
	var obj = workElem;

	var operMode = data.operMode;
	if ("modify" == operMode) {
		if (0 < indicatorAddrA.trim().length) {
			obj.childNodes[1].setAttribute("fill", "green");
			obj.childNodes[1].id = "indicator" + indicatorAddrA;
		} else {
			obj.childNodes[1].setAttribute("fill", "black");
			obj.childNodes[1].removeAttribute("id");
		}

		if (0 < indicatorAddrB.trim().length) {
			obj.childNodes[2].setAttribute("fill", "orange");
			obj.childNodes[2].id = "indicator" + indicatorAddrB;
		} else {
			obj.childNodes[2].setAttribute("fill", "black");
			obj.childNodes[2].removeAttribute("id");
		}

		if (0 < indicatorAddrC.trim().length) {
			obj.childNodes[3].setAttribute("fill", "red");
			obj.childNodes[3].id = "indicator" + indicatorAddrC;
		} else {
			obj.childNodes[3].setAttribute("fill", "black");
			obj.childNodes[3].removeAttribute("id");
		}

	} else {

		// 查找对象坐标
		var point = getCPoint(obj);
		var x = RADIUS;
		var y = RADIUS;
		var angle = parseFloat(-120);
		var r = RADIUS;

		var shape = document.createElementNS(svgns, "path");
		shape.setAttribute("indi", "true");
		var arc = "M" + x + "," + y + " L" + (x - r) + "," + y + " A" + r + ","
				+ r + " " + angle + " 0,1 " + (x + r / 2) + " "
				+ (y - Math.sqrt(3) * r / 2) + " L" + x + "," + y;
		shape.setAttribute("d", arc);
		shape.setAttribute("stroke", "#660000");
		if (0 < indicatorAddrA.trim().length) {
			shape.id = "indicator" + indicatorAddrA;
			shape.setAttribute("fill", "green");
		} else {
			shape.setAttribute("fill", "black");
		}
		obj.appendChild(shape);

		shape = document.createElementNS(svgns, "path");
		shape.setAttribute("indi", "true");
		arc = "M" + x + "," + y + " L" + (x + r / 2) + ","
				+ (y - Math.sqrt(3) * r / 2) + " A" + r + "," + r + " " + angle
				+ " 0,1 " + (x + r / 2) + " " + (y + Math.sqrt(3) * r / 2)
				+ " L" + x + "," + y;
		shape.setAttribute("d", arc);
		shape.setAttribute("stroke", "#660000");
		if (0 < indicatorAddrB.trim().length) {
			shape.id = "indicator" + indicatorAddrB;
			shape.setAttribute("fill", "orange");

		} else {
			shape.setAttribute("fill", "black");
		}
		obj.appendChild(shape);

		shape = document.createElementNS(svgns, "path");
		shape.setAttribute("indi", "true");
		arc = "M" + x + "," + y + " L" + (x + r / 2) + ","
				+ (y + Math.sqrt(3) * r / 2) + " A" + r + "," + r + " " + angle
				+ " 0,1 " + (x - r) + " " + y + " L" + x + "," + y;
		shape.setAttribute("d", arc);
		shape.setAttribute("stroke", "#660000");
		if (0 < indicatorAddrC.trim().length) {
			shape.id = "indicator" + indicatorAddrC;
			shape.setAttribute("fill", "red");

		} else {
			shape.setAttribute("fill", "black");
		}
		obj.appendChild(shape);
	}

	// 关闭弹出窗
	$("#igrouppopup").popup("close");

	try {
		var terminalId = $("#terminalid").val();
		var svgContent = $("#implementcontent").html();
		window.terminaljsi.saveSVGContent(terminalId, svgContent, 2);
	} catch (e) {
	}
	return false;
};

/**
 * 取消编辑指示器组，关闭之后触发方法
 */
var cancelEditIGroupAfterClose = function() {
	var obj = workElem;
	var iGroups = $("g[tags]");

	if (obj && obj.childNodes.length <= 1) {
		var elem = document.getElementById(obj.id);
		WORK_SVG.removeChild(elem);
	}
};

/**
 * 指示器组编辑取消按钮事件
 */
var cancelEditIgroup = function() {
	// 关闭弹出窗
	$("#igrouppopup").popup("close");
	return false;
};

// 根据指示器组节点元素画线
function makeLine(node1, node2, oldColor) {

	// 判断节点间是否已绘制连线，如果已绘制，则返回
	var lineId = isLinkedBetweenNodes(node1, node2);
	if ("" != lineId) {
		var line = $("#" + lineId, WORK_SVG);
		WORK_SVG.removeChild(line[0]);
		// return;
	}

	var point1 = getCPoint(node1);
	var point2 = getCPoint(node2);
	var point_c = new Array();
	computeBorder(point1, point2, point_c);

	var svg = document.createElementNS(svgns, 'g');
	svg.setAttribute("etype", "line");
	svg.setAttribute("line", "true");
	svg.setAttribute("sid", node1.id);
	svg.setAttribute("eid", node2.id);
	svg.id = "Line_" + node1.id + "_" + node2.id;

	var color = DEDAULT_LINE_COLOR;
	if (!oldColor) {
		// 当前线段集合
		CURR_LINES.push(svg.id);
	} else {
		color = oldColor;
	}

	var svg_line = document.createElementNS(svgns, "line");
	svg_line.x1.baseVal.value = point_c[0].x;
	svg_line.y1.baseVal.value = point_c[0].y;
	svg_line.x2.baseVal.value = point_c[1].x;
	svg_line.y2.baseVal.value = point_c[1].y;
	svg_line.style.stroke = color;
	svg_line.setAttribute("stroke-width", 4);
	svg_line.setAttribute("marker-end", "url(#markerArrow)");
	svg.appendChild(svg_line);

	var text = document.createElementNS(svgns, 'text');
	text.setAttribute("x", (point_c[0].x + point_c[1].x) / 2);
	text.setAttribute("y", (point_c[0].y + point_c[1].y) / 2);
	text.setAttribute("font-size", 14);
	text.setAttribute("fill", LINE_TEXT_COLOR);
	text.setAttribute("text-anchor", "middle");
	text.textContent = node1.id + " to " + node2.id;
	svg.appendChild(text);

	WORK_SVG.appendChild(svg);

	point_c.length = 0;
}

/**
 * 判断节点间是否存在连线，如果存在则返回连线的id
 * 
 * @param {}
 *            node1
 * @param {}
 *            node2
 * @return {String}
 */
var isLinkedBetweenNodes = function(node1, node2) {

	var lineId = "Line_" + node1.id + "_" + node2.id;
	var obj = $("#" + lineId, WORK_SVG);

	if (0 < obj.length) { // 对象存在
		return lineId;
	}

	var lineId = "Line_" + node2.id + "_" + node1.id; // 交换节点前后的顺序
	var obj = $("#" + lineId, WORK_SVG);
	if (0 < obj.length) {
		return lineId;
	}

	return "";
};

// 计算画线的边界点
function computeBorder(point1, point2, pArray) {
	var r = RADIUS;
	var x_interval = point1.x - point2.x;
	var y_interval = point1.y - point2.y;

	var x_deta = Math.abs(x_interval);
	var y_deta = Math.abs(y_interval);

	var x_r_deta = (r * x_deta)
			/ Math.pow((Math.pow(x_deta, 2) + Math.pow(y_deta, 2)), 0.5);
	var y_r_deta = (r * y_deta)
			/ Math.pow((Math.pow(x_deta, 2) + Math.pow(y_deta, 2)), 0.5);

	var b_point1_x;
	var b_point1_y;
	var b_point2_x;
	var b_point2_y;

	if (x_interval < 0) {
		b_point1_x = point1.x + x_r_deta;
		b_point2_x = point2.x - x_r_deta - Math.pow(125, 0.5) * x_deta
				/ Math.pow((Math.pow(x_deta, 2) + Math.pow(y_deta, 2)), 0.5)
				- 1;
	} else {
		b_point1_x = point1.x - x_r_deta;
		b_point2_x = point2.x + x_r_deta + Math.pow(125, 0.5) * x_deta
				/ Math.pow((Math.pow(x_deta, 2) + Math.pow(y_deta, 2)), 0.5)
				+ 1;
	}

	if (y_interval < 0) {
		b_point1_y = point1.y + y_r_deta;
		b_point2_y = point2.y - y_r_deta - (Math.pow(125, 0.5) * y_deta)
				/ Math.pow((Math.pow(x_deta, 2) + Math.pow(y_deta, 2)), 0.5)
				- 1;
	} else {
		b_point1_y = point1.y - y_r_deta;
		b_point2_y = point2.y + y_r_deta + (Math.pow(125, 0.5) * y_deta)
				/ Math.pow((Math.pow(x_deta, 2) + Math.pow(y_deta, 2)), 0.5)
				+ 1;
	}

	point1 = new Point(b_point1_x, b_point1_y);
	pArray.push(point1);
	point2 = new Point(b_point2_x, b_point2_y);
	pArray.push(point2);
}

/**
 * 判斷新增加的位置是否临近其他元素，目前为指示器组临近范围确定
 * 
 * @param {}
 *            point
 */
var isValidCoord = function(point) {

	var isValid = true;

	var objs = $("g[tags]");
	for (var i = 0; i < objs.length; i++) {
		var obj = objs[i];
		var epoint = getCPoint(obj);

		var distance = Math.pow((Math.pow(epoint.x - point.x, 2) + Math.pow(
						epoint.y - point.y, 2)), 0.5);

		if (distance < 2 * RADIUS + NEAR_FACTOR) {
			isValid = false;
			break;
		}

	}

	return isValid;
}

/**
 * 拖拽终端/指示器组后重绘连线
 * 
 * @param {}
 *            obj
 */
var repaintLine = function(obj) {
	var elem = obj.el;
	var lines = $("g[line]");
	var len = lines.length;
	for (var i = len - 1; i >= 0; i--) {
		var line = lines[i];
		var sNode = document.getElementById(lines[i].getAttribute("sid"));
		var eNode = document.getElementById(lines[i].getAttribute("eid"));

		if (elem == sNode || elem == eNode) {
			var oldColor = line.childNodes[0].style.stroke;
			WORK_SVG.removeChild(line);
			makeLine(sNode, eNode, oldColor);
		}
	}
};

/**
 * 在SVG上凸显指示器组
 */
var searchIndicators = function() {
	var searchAddr = $("#searchaddr", $("#searchpopup")).val().toUpperCase();

	var igroups = $("g[etype='indicator']"); // 检索指示器组

	var isExist = false
	for (var i = 0; i < igroups.length; i++) {
		var igroup = igroups[i];
		var children = igroup.childNodes;
		for (var j = 1; j <= 3; j++) {
			var iid = children[j].id;
			if (iid && iid.substring(9).toUpperCase().indexOf(searchAddr) != -1) {
				changeSelectedStatus(igroup, 1);
				isExist = true;
				break;
			}
		}
	}

	if (isExist) { // 如果在SVG上存在该地址的指示器组，则关闭弹出框
		$("#searchpopup").popup("close");
	}
};

// 按返回键是保存
var onBackKey = function() {
	try {
		var terminalId = $("#terminalid").val();
		var svgContent = $("#implementcontent").html();
		window.terminaljsi.saveSVGContent(terminalId, svgContent, 4);

		var display = $("#showscheme").hasClass("ui-panel-open");
		if (display == false) {

			$("#showscheme").panel("open");

			window.debugjsi.stopFallback();
		}
	} catch (e) {
	}
}
// 通信自测的目的指示器地址
var COMM_TARGET_INDICATOR_ADDR;
// 通信操作类型（通信自测、多级链路通信）
var COMM_OPER_TYPE;
// 通信状态，下发报文，收到回应为正常
var COMM_STATUS = true;
// 通信失败的上限
var MAX_COUNT_COMM_FAIL = 3;
// 当前通信失败的次数
var COUNT_COMM_FAIL = 0;
// 日志最大的数目
var MAX_COUNT_LOG = 50;
// 当前的日志数
var COUNT_LOG = 0;
// 通信自测超时
var TEST_COMM_TIME_OUT;
/**
 * 检测通信状态
 */
var testComm = function() {

	COMM_OPER_TYPE = "commautotest";

	if (null != DEFAULT_IGROUP_ID && undefined != DEFAULT_IGROUP_ID
			&& 0 < DEFAULT_IGROUP_ID.trim().length) {
		// 获取SVG中指示器组对象
		var iGroup = document.getElementById(DEFAULT_IGROUP_ID);

		// 依次判断是否安装了CBA三相指示器
		for (var i = 3; i >= 1; i--) {
			if (null != iGroup) {
				var iId = iGroup.childNodes[i].id;
				if (null != iId && 0 < iId.length) {
					COMM_TARGET_INDICATOR_ADDR = iId.substring(9);
					break;
				}
			}
		}
	}

	if (!COMM_STATUS) {

		++COUNT_COMM_FAIL;
	}

	// 超过MAX_COUNT_COMM_FAIL通信失败，则停止下发
	if (MAX_COUNT_COMM_FAIL <= COUNT_COMM_FAIL) {
		clearCommAutoTestTimeout();
		clearSelectedStatus();

		var msg = "通信失败, 连续 " + MAX_COUNT_COMM_FAIL + " 次未收到目标指示器的响应!";
		showMsg(msg, 10000);
		addLog(msg);

		return;
	}

	var msg = "目标指示器地址是" + COMM_TARGET_INDICATOR_ADDR + "!";
	showMsg(msg, 5000);
	addLog(msg);

	try {
		COMM_STATUS = false;
		window.debugjsi.getIndicatorVersion(COMM_TARGET_INDICATOR_ADDR);
	} catch (e) {
	}

	TEST_COMM_TIME_OUT = setTimeout("testComm()", SERIAL_PORT_TIME_OUT / 2
					* 1000);
};

/**
 * 取消通信自测得定时器
 */
var clearCommAutoTestTimeout = function() {
	IS_START_TIME_OUT = false;

	$("#commautotestbtn").val("通信自测");
	$("#commautotestbtn").button({
				theme : 'f'
			}).button("refresh");

	clearTimeout(TEST_COMM_TIME_OUT);
};

/**
 * 插入日志
 * 
 * @param {}
 *            msg
 */
var addLog = function(msg) {

	var date = new Date();
	var time = getNowDatetime(date);
	var terminalId = $("#terminalid").val();
	var params = "{'content': '" + msg + "', 'time': '" + date.getTime()
			+ "', 'terminalid': '" + terminalId + "'}";
	try {
		window.logjsi.addLog(params);
	} catch (e) {
	}

	createMsgWithBox(msg, time);
};

/**
 * 生成带箭头提示框的消息
 */
var createMsgWithBox = function(msg, time) {

	if (++COUNT_LOG > MAX_COUNT_LOG) {
		$(".log-div", $("#impllogtabcontent")).empty();
		COUNT_LOG = 1;
		CURR_PAGE = 1;
	}

	var content = "<p class='time-list'>" + time
			+ "<p><div class=\"ark-poptip\">"
			+ "<div class=\"ark-poptip-shadow\">"
			+ "<div class=\"ark-poptip-container\">"
			+ "<div class=\"ark-poptip-arrow ark-poptip-arrow-a\">"
			+ "<em>◆</em><span>◆</span></div>"
			+ "<div class=\"ark-poptip-content\">" + msg
			+ "</div></div></div></div></div>"

	$(".log-div", $("#impllogtabcontent")).prepend(content);
};

/**
 * 下行报文的操作方法
 * 
 * @param {}
 *            frame
 */
var showOutFrame = function(frame) {

	var msg = "";
	if ("commautotest" == COMM_OPER_TYPE) {
		msg = "通信自测报文下发成功!";
	} else if ("relaycommtest" == COMM_OPER_TYPE) {
		msg = "多级通信测试报文下发成功!"
	} else if ("archive" == COMM_OPER_TYPE) {
		msg = "组网档案报文下发成功!";
	} else if ("network" == COMM_OPER_TYPE) {
		msg = "启动组网报文下发成功!";
	} else if ("getrtcurrent" == COMM_OPER_TYPE) {
		msg = "读取实时电流报文下发成功!";
	} else if ("getsleeptime" == COMM_OPER_TYPE) {
		msg = "读取休眠时间报文下发成功!";
	} else if ("setsleeptime" == COMM_OPER_TYPE) {
		msg = "设置休眠时间报文下发成功!";
	} else if ("getindicatorver" == COMM_OPER_TYPE) {
		msg = "读取指示器版本报文下发成功!";
	} else if ("indicatorflip" == COMM_OPER_TYPE) {
		msg = "指示器翻牌/复归报文下发成功!";
	} else if ("getindicatorelecfield" == COMM_OPER_TYPE) {
		msg = "读取实时电场报文下发成功!";
	} else if ("resetindicatorcommaddr" == COMM_OPER_TYPE) {
		msg = "重设指示器模块地址报文下发成功!";
	} else if ("getterminalversion" == COMM_OPER_TYPE) {
		msg = "读取终端版本信息报文下发成功!";
	} else if ("getterminalcommstatus" == COMM_OPER_TYPE) {
		msg = "读取终端通信状态报文下发成功!";
	} else if ("getterminaladdr" == COMM_OPER_TYPE) {
		msg = "读取终端地址报文下发成功!";
	} else if ("setterminaladdr" == COMM_OPER_TYPE) {
		msg = "设置终端地址报文下发成功!";
	} else if ("getterminalcommparams" == COMM_OPER_TYPE) {
		msg = "读取终端通信参数报文下发成功!";
	} else if ("setterminalcommparams" == COMM_OPER_TYPE) {
		msg = "设置终端通信参数报文下发成功!";
	} else if ("resetterminal" == COMM_OPER_TYPE) {
		msg = "复位终端报文下发成功!";
	}

	showMsg(msg);
	addLog(msg + "<br/><div style=\"color: gray\">" + frame + "</div>");

	var arr = frame.split(" ");
	var indicatorAddr;
	if ("commautotest" == COMM_OPER_TYPE) {
		indicatorAddr = arr[10] + arr[9] + arr[8];
		var params = "{'indicatorAddr': '" + indicatorAddr
				+ "', 'singleComm':'0'}";
		addOrModifyIStatus(params);
	} else if ("relaycommtest" == COMM_OPER_TYPE) {
		var len = parseInt(arr[1], 16);
		var offset = 8;
		if (len > 9) {
			var time = (len - 6) / 3;
			for (var i = 0; i < time; i++) {
				indicatorAddr = arr[2 + offset] + arr[1 + offset] + arr[offset];
				var params = "{'indicatorAddr': '" + indicatorAddr
						+ "', 'multiComm':'0'}";
				addOrModifyIStatus(params);
				offset += 3;
			}
		}
	} else if ("network" == COMM_OPER_TYPE) {
		for (var j = 1; j < RELAY_NODES.length; j++) {
			var node = RELAY_NODES[j];

			for (var i = 0; i < 3; i++) {
				var iId = node.childNodes[i + 1].id;
				if (null != iId && 0 < iId.length) {
					indicatorAddr = iId.substring(9);
					var params = "{'indicatorAddr': '" + indicatorAddr
							+ "', 'network':'0'}";
					addOrModifyIStatus(params);
				}
			}
		}
	}
}

/**
 * 收到上行报文的操作方法
 * 
 * @param {}
 *            frame
 */
var showInFrame = function(frame) {

	var msg = "";
	if ("EE EE EE EE EE EE EE EE EE EE" == frame.trim()) {
		msg = "收到调试模块超时报文, 通信超时!";
		if ("commautotest" == COMM_OPER_TYPE
				&& MAX_COUNT_COMM_FAIL <= COUNT_COMM_FAIL) {
			clearCommAutoTestTimeout();
		} else if ("relaycommtest" == COMM_OPER_TYPE
				|| "archive" == COMM_OPER_TYPE || "network" == COMM_OPER_TYPE) {
			clear();
		}

		clearSelectedStatus();

		showMsg(msg);
		addLog(msg);
	} else {
		msg = "收到响应报文!";
		showMsg(msg);
		addLog(msg + "<br/><div style=\"color: gray\">" + frame + "</div>");

		var arr = frame.split(" ");
		var indicatorAddr;
		if ("commautotest" == COMM_OPER_TYPE) {
			indicatorAddr = arr[4] + arr[3] + arr[2];
			var params = "{'indicatorAddr': '" + indicatorAddr
					+ "', 'singleComm':'1'}";
			addOrModifyIStatus(params);
		} else if ("relaycommtest" == COMM_OPER_TYPE) {
			var len = parseInt(arr[1], 16) - 2;
			var offset = 2;
			indicatorAddr = arr[2 + offset] + arr[1 + offset] + arr[offset];
			var params = "{'indicatorAddr': '" + indicatorAddr
					+ "', 'multiComm':'1'}";
			addOrModifyIStatus(params);

			if (len > 12) {
				var time = (len - 12) / 6;
				offset += 12;
				for (var i = 0; i < time; i++) {
					indicatorAddr = arr[2 + offset] + arr[1 + offset]
							+ arr[offset];
					var params = "{'indicatorAddr': '" + indicatorAddr
							+ "', 'multiComm':'1'}";
					addOrModifyIStatus(params);
					offset += 6;
				}
			}
		} else if ("network" == COMM_OPER_TYPE) {
			for (var j = 1; j < RELAY_NODES.length; j++) {
				var node = RELAY_NODES[j];

				for (var i = 0; i < 3; i++) {
					var iId = node.childNodes[i + 1].id;
					if (null != iId && 0 < iId.length) {
						indicatorAddr = iId.substring(9);
						var params = "{'indicatorAddr': '" + indicatorAddr
								+ "', 'network':'1'}";
						addOrModifyIStatus(params);
					}
				}
			}
		}
	}
}

/**
 * 通信自测的回调方法（查询目标指示器的指示器版本信息）
 * 
 * @param {}
 *            data
 */
var getIndicatorVersionCallback = function(data) {
	COMM_STATUS = true;
	COUNT_COMM_FAIL = 0;

	var msg = "点对点通信正常!";
	showMsg(msg, 10000);
	addLog(msg);

	// data = JSON.parse(data);
	// var info = "硬件版本: " + data.hardware + "; " + "软件版本: " + data.software;
	// addLog("指示器版本信息: " + info);
}

/**
 * 不能删除
 */
var enableBtn = function() {
}

// 多级指示器的分支
var BRANCHES_RELAY_INDICATORS = new Array();
// 当前分支
var CURR_BRANCH;
// 发送成功的分支数
var COUNT_BRANCH_SUCC = 0;
// 当前线段集合
var CURR_LINES = new Array();
// 中继节点
var RELAY_NODES = new Array();
// 已选择的指示器组/终端集合
var IG_TERM_SELECTED_ARR = new Array();
/**
 * 多级通信测试
 */
var relayCommTest = function() {

	if (1 >= RELAY_NODES.length) {
		clear();
		clearSelectedStatus();
		return;
	}

	if (null != TIME_OUT && 0 < BRANCHES_RELAY_INDICATORS.length) {
		var msg = "";
		if ("relaycommtest" == COMM_OPER_TYPE) {
			msg = "多级通信正在测试中, 请稍候...";
		} else if ("archive" == COMM_OPER_TYPE || "network" == COMM_OPER_TYPE) {
			msg = "终端正在组网中, 请稍候...";
		}

		showMsg(msg);
		addLog(msg);
		return;
	}

	for (var i = 0; i < 3; i++) {
		for (var j = 0; j < RELAY_NODES.length; j++) {
			var node = RELAY_NODES[j];

			if (BRANCHES_RELAY_INDICATORS[i] == undefined) {
				BRANCHES_RELAY_INDICATORS[i] = new Array();
			}

			if ("Terminal" == node.getAttribute("id")) { // 终端
				var wirelessAddr = $("#twirelessaddr").val();
				BRANCHES_RELAY_INDICATORS[i].push(wirelessAddr);
			} else {
				var iId = node.childNodes[i + 1].id;
				if (null != iId && 0 < iId.length) {
					var indicatorAddr = iId.substring(9);
					BRANCHES_RELAY_INDICATORS[i].push(indicatorAddr);
				} else {
					BRANCHES_RELAY_INDICATORS[i].push("HHHHHH");
				}
			}
		}
	}

	// 调整，中间指示器组未完全装完，利用邻居节点
	for (var j = 1; j < RELAY_NODES.length; j++) {

		var a = BRANCHES_RELAY_INDICATORS[0][j];
		var b = BRANCHES_RELAY_INDICATORS[1][j];
		var c = BRANCHES_RELAY_INDICATORS[2][j];

		if ("HHHHHH" == a) {
			BRANCHES_RELAY_INDICATORS[0][j] = ("HHHHHH" == b ? c : b);
		}

		if ("HHHHHH" == b) {
			BRANCHES_RELAY_INDICATORS[1][j] = ("HHHHHH" == c ? a : c);
		}

		if ("HHHHHH" == c) {
			BRANCHES_RELAY_INDICATORS[2][j] = ("HHHHHH" == a ? b : a);
		}
	}

	var msg = "已选择指示器组/终端依次是 " + IG_TERM_SELECTED_ARR.toString();
	showMsg(msg);
	addLog(msg);

	// 判断第一个节点是否为终端，弹出提示框，选择“通信测试”和“组网”
	var nodeId = RELAY_NODES[0].id;
	if ("Terminal" == nodeId) {
		$("#triggerdebugconfirmpopup").click();

		// 通信測試 和 組網操作选择对话框动态绑定事件
		// 通信测试绑定事件
		$("#tcommtestbtn").unbind("click").bind("click", function() {
					startRelayCommTest();
					$("#debugconfirmpopup").popup("close");
					return;
				});

		// 取消绑定事件
		$("#tcanclebtn").unbind("click").bind("click", function() {
					clear();
					clearSelectedStatus();
					$("#debugconfirmpopup").popup("close");
					return;
				});

		// 组网绑定事件
		$("#tnetworkbtn").unbind("click").bind("click", function() {
			try {
				var indicatorIds = BRANCHES_RELAY_INDICATORS[0] + "_"
						+ BRANCHES_RELAY_INDICATORS[1] + "_"
						+ BRANCHES_RELAY_INDICATORS[2];
				var terminalId = $("#terminalid").val();

				window.indicatorjsi.setBranchLevel(indicatorIds, terminalId);
			} catch (e) {
			}
			$("#debugconfirmpopup").popup("close");

			return;
		});
		return;
	}

	startRelayCommTest();
}

/**
 * 开始多级通信测试
 */
var startRelayCommTest = function() {
	// 取消通信自测
	clearCommAutoTestTimeout();

	var msg = "多级通信测试已启动!";
	showMsg(msg);
	addLog(msg);

	COMM_OPER_TYPE = "relaycommtest";

	for (var i = 0; i < 3; i++) {
		if ("HHHHHH" != BRANCHES_RELAY_INDICATORS[i][0]) {
			CURR_BRANCH = i;

			testBranchComm();
			break;
		}
	}
};

/**
 * 开始某分支的通信测试
 */
var testBranchComm = function() {

	COMM_STATUS = false;
	var params = BRANCHES_RELAY_INDICATORS[CURR_BRANCH].toString();
	BRANCHES_RELAY_INDICATORS[CURR_BRANCH] = new Array();

	var msg = "多级通信的指示器依次是 " + params + "[ " + getPhase(CURR_BRANCH) + " ]!";
	showMsg(msg, 5000);
	addLog(msg);

	window.debugjsi.getRelayRTStatus(params);

	TIME_OUT = setTimeout(function() {
				if (!COMM_STATUS) {
					var msg = "多级通信超时!";
					showMsg(msg, 10000);
					addLog(msg);

					clear();
					clearSelectedStatus();
				}
			}, SERIAL_PORT_TIME_OUT * 1000);
};

/**
 * 清空参数
 */
var clear = function() {

	clearTimeout(TIME_OUT);
	TIME_OUT = null;

	COMM_STATUS = false;
	CURR_BRANCH = 0;
	COUNT_BRANCH_SUCC = 0;

	CURR_LINES = new Array();
	BRANCHES_RELAY_INDICATORS = new Array();
	RELAY_NODES = new Array();
	IG_TERM_SELECTED_ARR = new Array();
};

/**
 * 获取相位
 * 
 * @param {}
 *            num
 */
var getPhase = function(num) {
	return num == 0 ? "A相" : (num == 1 ? "B相" : "C相");
}

/**
 * 读指示器实时状态的回调函数
 * 
 * @param {}
 *            data
 */
var getIndicatorRTStatusCallback = function(data) {

	clearTimeout(TIME_OUT);
	if (COMM_OPER_TYPE == "getrtcurrent") { // 如果是召测实时电流
		data = JSON.parse(data);
		$("#rtcurrent", $("#rtcurrentpopup")).html(data.lineLoad + " A");
		$("#rtcurrentlabel", $("#rtcurrentpopup")).show();

		var obj = $("#rtcurrentbtn", $("#rtcurrentpopup"));
		endTimeout(obj, "读取");

		return;
	}

	COMM_STATUS = true;

	++COUNT_BRANCH_SUCC;
	while (true) {
		CURR_BRANCH++;
		if (CURR_BRANCH == 3) {

			var msg = "多级通信正常!";
			showMsg(msg, 10000);
			addLog(msg);

			var currColor = COUNT_BRANCH_SUCC == 3
					? ALL_COMM_SUCC_LINE_COLOR
					: PART_COMM_SUCC_LINE_COLOR;
			updateLineColor(currColor);

			clear();
			clearSelectedStatus();
			break;
		} else {

			var currColor = PART_COMM_SUCC_LINE_COLOR;
			updateLineColor(currColor);

			if ("HHHHHH" != BRANCHES_RELAY_INDICATORS[CURR_BRANCH][0]) {
				testBranchComm();
				break;
			}
		}
	}
};

/**
 * 设置分支路径的回调方法
 */
var setBranchLevelCallback = function(cBranch) {
	if (0 != cBranch) {
		// 添加分支级别信息
		for (var i = 1; i < RELAY_NODES.length; i++) {
			var node = RELAY_NODES[i];

			// 如果存在文本，则先去除
			var textNode = node.childNodes[4];
			if (null != textNode) {
				node.removeChild(textNode);
			}

			var point = getCPoint(node);
			var text = document.createElementNS(svgns, 'text');
			text.setAttribute("x", 2 * RADIUS + 5);
			text.setAttribute("y", RADIUS + 14 / 2);
			text.setAttribute("font-size", 14);
			text.setAttribute("fill", IGROUP_TEXT_COLOR);
			text.textContent = Math.ceil(cBranch / 3) + " - " + i;
			node.appendChild(text);
		}
	}

	startNetworkArchive();
}

/**
 * 开始组网档案下发
 */
var startNetworkArchive = function() {
	// 取消通信自测
	clearCommAutoTestTimeout();

	var msg = "组网档案下发已启动!";
	showMsg(msg);
	addLog(msg);

	COMM_OPER_TYPE = "archive";

	for (var i = 0; i < 3; i++) {
		if ("HHHHHH" != BRANCHES_RELAY_INDICATORS[i][1]) {
			CURR_BRANCH = i;

			setNetworkArchive();
			break;
		}
	}
};

/**
 * 开始某分支的组网档案下发
 */
var setNetworkArchive = function() {

	COMM_STATUS = false;
	var indicatorAddrs = BRANCHES_RELAY_INDICATORS[CURR_BRANCH].toString();
	BRANCHES_RELAY_INDICATORS[CURR_BRANCH] = new Array();

	var msg = "下发档案的指示器依次是 " + indicatorAddrs.substring(7) + "[ "
			+ getPhase(CURR_BRANCH) + " 分支 ]!";
	showMsg(msg, 5000);
	addLog(msg);

	try {
		window.debugjsi.setNetworkArchive(indicatorAddrs);
	} catch (e) {
	}

	TIME_OUT = setTimeout(function() {
				if (!COMM_STATUS) {
					var msg = "组网档案下发超时!";
					showMsg(msg, 10000);
					addLog(msg);

					clear();
					clearSelectedStatus();
				}
			}, SERIAL_PORT_TIME_OUT * 2 * 1000);
};

/**
 * 下发组网档案的回调方法
 * 
 * @param {}
 *            data
 */
var setNetworkArchiveCallback = function(data) {

	clearTimeout(TIME_OUT);

	COMM_STATUS = true;

	++COUNT_BRANCH_SUCC;
	while (true) {

		data = JSON.parse(data);
		var actionReply = data.actionReply;

		var msg = "";
		if ("OK" != actionReply) {
			msg = "档案下发失败!";
			showMsg(msg, 10000);
			addLog(msg);

			clear();
			clearSelectedStatus();

			return;
		}

		CURR_BRANCH++;
		if (CURR_BRANCH == 3) {

			var currColor = ALL_COMM_SUCC_LINE_COLOR;
			updateLineColor(currColor);

			var msg = "档案下发成功, 即将启动组网...";
			showMsg(msg, 5000);
			addLog(msg);

			try {

				msg = "组网已启动!";
				showMsg(msg, 5000);
				addLog(msg);

				COMM_OPER_TYPE = "network";

				var wirelessAddr = $("#twirelessaddr").val();
				window.debugjsi.startNetwork(wirelessAddr);
			} catch (e) {
			}
			break;
		} else {

			var currColor = PART_COMM_SUCC_LINE_COLOR;
			updateLineColor(currColor);

			if ("HHHHHH" != BRANCHES_RELAY_INDICATORS[CURR_BRANCH][0]) {
				setNetworkArchive();
				break;
			}
		}
	}
};

/**
 * 启动组网的回调方法
 * 
 * @param {}
 *            data
 */
var startNetworkCallback = function(data) {

	data = JSON.parse(data);
	var actionReply = data.actionReply;

	var msg = "OK" == actionReply ? "组网成功!" : "组网失败!";
	showMsg(msg, 10000);
	addLog(msg);

	if ("OK" == actionReply) {
		var currColor = NETWORK_SUCC_LINE_COLOR;
		updateLineColor(currColor);
	}

	clear();
	clearSelectedStatus();
};

/**
 * 修改线段颜色
 * 
 * @param {}
 *            color
 */
var updateLineColor = function(color) {
	for (var i = 0; i < CURR_LINES.length; i++) {
		var line = document.getElementById(CURR_LINES[i]);
		line.childNodes[0].style.stroke = color;
	}
};

/** ------------------iScroll上拉事件相关----------------------------------- */
var dataScroll, pullUpEl, pullUpOffset;
var CURR_PAGE = 1;
/**
 * 上拉事件
 */
var pullUpAction = function() {

	queryLogsByPage()

	// 刷新
	dataScroll.refresh();
};

/**
 * 初始化iScroll控件
 */
function loaded() {

	pullUpEl = $('#pullup');
	pullUpOffset = pullUpEl.attr("offsetHeight");

	dataScroll = new iScroll('wrapper', {
				scrollbarClass : 'myScrollbar', /* 重要样式 */
				useTransition : false,
				onRefresh : function() {
					if (pullUpEl.hasClass('loading')) {
						pullUpEl.removeClass('loading');
						$('.pullup-label', pullUpEl).html('上拉加载更多...');
					}
				},
				onScrollMove : function() {
					if (this.y > 0) {
						pullUpEl.removeClass('flip');
						return;
					}

					if (this.y < (this.maxScrollY - 5)
							&& !pullUpEl.hasClass('flip')) {
						pullUpEl.removeClass();
						pullUpEl.addClass('flip');
						$('.pullup-label', pullUpEl).html('松手开始更新...');
						this.maxScrollY = this.maxScrollY;
					} else if (this.y > (this.maxScrollY + 5)
							&& pullUpEl.hasClass('flip')) {
						pullUpEl.removeClass();
						$('.pullup-label', pullUpEl).html('上拉加载更多...');
						this.maxScrollY = pullUpOffset;
					}
				},
				onScrollEnd : function() {
					if (pullUpEl.hasClass('flip')) {
						pullUpEl.removeClass();
						pullUpEl.addClass('loading');
						$('.pullup-label', pullUpEl).html('加载中...');
						pullUpAction();
					}
				}
			});
};
/** ----------------------------------------------------- */

var LAST_TIME;
/**
 * 分页查询日志
 */
var queryLogsByPage = function() {

	var time = $(".time-list:last").html();
	var longTime = 0;
	if (undefined == time || null == time || 0 == time.trim().lenth) {
		longTime = 0;
	} else {
		var date = new Date(time.replace(/\-/g, "\/"));
		longTime = date.getTime();
	}
	if (LAST_TIME == longTime) {
		showMsg("已加载所有日志!");
		return;
	}
	LAST_TIME = longTime;

	var terminalId = $("#terminalid").val();
	try {
		var params = "{'pagesize': '6', 'page': '" + CURR_PAGE
				+ "', 'terminalid': '" + terminalId + "', 'time': '" + longTime
				+ "'}";
		window.logjsi.queryLogsByPage(params);
	} catch (e) {
	}
};

/**
 * 分页查询日志的回调方法
 * 
 * @param {}
 *            data
 */
var queryLogsByPageCallback = function(data) {

	for (var i = 0; i < data.length; i++) {
		var date = new Date();
		date.setTime(data[i].time);
		var content = "<p class='time-list'>" + getNowDatetime(date)
				+ "<p><div class=\"ark-poptip\">"
				+ "<div class=\"ark-poptip-shadow\">"
				+ "<div class=\"ark-poptip-container\">"
				+ "<div class=\"ark-poptip-arrow ark-poptip-arrow-a\">"
				+ "<em>◆</em><span>◆</span></div>"
				+ "<div class=\"ark-poptip-content\">" + data[i].content
				+ "</div></div></div></div></div>"

		$(".log-div", $("#impllogtabcontent")).append(content);
	}

	CURR_PAGE++;
};

/**
 * 添加或修改指示器状态
 */
var addOrModifyIStatus = function(params) {
	try {
		window.indicatorstatusjsi.addOrModifyIStatus(params);
	} catch (e) {
	}
};

/**
 * 查询指示器状态
 * 
 * @param {}
 *            terminalId
 */
var queryIndicatorStatuses = function(terminalId) {
	try {
		window.indicatorstatusjsi.queryIndicatorStatuses(terminalId);
	} catch (e) {
	}
};

/**
 * 查询终端下的指示器状态回调方法
 * 
 * @param {}
 *            data
 */
var queryIndicatorStatusesCallback = function(data) {

	var content = "<table class='hovertable'><tr><th width='40%'>指示器地址</th><th width='20%'>点对点</th><th width='20%'>多级</th><th width='20%'>组网</th></tr>";
	for (var i = 0; i < data.length; i++) {
		content += "<tr><td>"
				+ data[i].indicator.indicatoraddr.toUpperCase()
				+ "</td><td align='center'>"
				+ (data[i].singlecomm == 1 ? "<img src='" + basePath
						+ "image/right.PNG' alt='true'/>" : "")
				+ "</td><td align='center'>"
				+ (data[i].multicomm == 1 ? "<img src='" + basePath
						+ "image/right.PNG' alt='true'/>" : "")
				+ "</td><td align='center'>"
				+ (data[i].network == 1 ? "<img src='" + basePath
						+ "image/right.PNG' alt='true'/>" : "") + "</td></tr>";
	}
	content += "</table>";

	$("#implstatustabcontent").html(content);
};

/**
 * 开始超时时间计时
 * 
 * @param {}
 *            obj
 * @param {}
 *            btnValue
 */
var startTimeout = function(obj, btnValue) {

	// 禁用按钮
	$(obj).button("disable");
	$(".ui-btn-text", $(obj).parent()).html("加载中...");

	// 重新启用按钮
	TIME_OUT = setTimeout(function() {
				$(obj).button("enable");
				$(".ui-btn-text", $(obj).parent()).html(btnValue);
			}, SERIAL_PORT_TIME_OUT * 1000);
};

/**
 * 完成超时时间计时
 * 
 * @param {}
 *            obj
 * @param {}
 *            btnValue
 */
var endTimeout = function(obj, btnValue) {

	clearTimeout(TIME_OUT);
	// 启用按钮
	obj.button("enable");
	$(".ui-btn-text", obj.parent()).html(btnValue);
};
/**
 * 显示实时电流窗口
 */
var showRTCurrentWin = function() {

	$("#rtcurrentbtn", $("#rtcurrentpopup")).parent().css("width", "105px");

	$("#rtcurrentinfo", $("#rtcurrentpopup")).hide();
	$("#aphase", $("#rtcurrentpopup")).prop("checked", false)
			.checkboxradio("refresh");
	$("#bphase", $("#rtcurrentpopup")).prop("checked", false)
			.checkboxradio("refresh");
	$("#cphase", $("#rtcurrentpopup")).prop("checked", false)
			.checkboxradio("refresh");
	$(".tipcontentspan", $("#rtcurrentpopup")).html("");
	$("#rtindicatoraddr", $("#rtcurrentpopup")).html("");
	$("#rtcurrent", $("#rtcurrentpopup")).html("");

	var obj = $("#rtcurrentbtn", $("#rtcurrentpopup"));
	endTimeout(obj, "读取");

	$("#triggerrtcurrentpopup").click();
	$("#rtcurrentbtn", $("#rtcurrentpopup")).unbind("click").bind("click",
			function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				// 清空实时电流
				$("#rtcurrent", $("#rtcurrentpopup")).html("");

				var indicatorAddr = $("#rtindicatoraddr", $("#rtcurrentpopup"))
						.html();

				// 清空提示
				$(".tipcontentspan", $("#rtcurrentpopup")).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", $("#rtcurrentpopup"))
							.html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				startTimeout(this, "读取");
				COMM_OPER_TYPE = "getrtcurrent";
				try {
					window.debugjsi.getIndicatorRTStatus(indicatorAddr);
				} catch (e) {
				}
			});
};

/**
 * 显示休眠时间窗口
 */
var showSleepTimeWin = function() {

	// 修改按钮的宽度
	$("#readsleeptimebtn", $("#sleeptimepopup")).parent().css("width", "105px");
	$("#setsleeptimebtn", $("#sleeptimepopup")).parent().css("width", "105px");

	// 清空表单
	$("#stindicatorinfo", $("#sleeptimepopup")).hide();
	$("#aphase", $("#sleeptimepopup")).prop("checked", false)
			.checkboxradio("refresh");
	$("#bphase", $("#sleeptimepopup")).prop("checked", false)
			.checkboxradio("refresh");
	$("#cphase", $("#sleeptimepopup")).prop("checked", false)
			.checkboxradio("refresh");
	$(".tipcontentspan", $("#sleeptimepopup")).html("");
	$("#stindicatoraddr", $("#sleeptimepopup")).html("");

	var obj = $("#readsleeptimebtn", $("#sleeptimepopup"));
	endTimeout(obj, "读取");

	obj = $("#setsleeptimebtn", $("#sleeptimepopup"));
	endTimeout(obj, "设置");

	// 打开窗口
	$("#triggersleeptimepopup").click();

	// 绑定读取事件
	$("#readsleeptimebtn", $("#sleeptimepopup")).unbind("click").bind("click",
			function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				var indicatorAddr = $("#stindicatoraddr", $("#sleeptimepopup"))
						.html();

				// 清空提示
				$(".tipcontentspan", $("#sleeptimepopup")).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", $("#sleeptimepopup"))
							.html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				startTimeout(this, "读取");
				COMM_OPER_TYPE = "getsleeptime";
				try {
					window.debugjsi.getSleepTime(indicatorAddr);
				} catch (e) {
				}
			});

	// 绑定设置事件
	$("#setsleeptimebtn", $("#sleeptimepopup")).unbind("click").bind("click",
			function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				var indicatorAddr = $("#stindicatoraddr", $("#sleeptimepopup"))
						.html();

				// 清空提示
				$(".tipcontentspan", $("#sleeptimepopup")).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", $("#sleeptimepopup"))
							.html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				var sleepTime = $("#sleeptime", $("#sleeptimepopup")).val();

				startTimeout(this, "设置");
				COMM_OPER_TYPE = "setsleeptime";
				try {
					window.debugjsi.setSleepTime(indicatorAddr, sleepTime);
				} catch (e) {
				}
			});
};

/**
 * 读休眠时间的回调函数
 * 
 * @param {}
 *            data
 */
var getSleepTimeCallback = function(data) {

	var obj = $("#readsleeptimebtn", $("#sleeptimepopup"));
	endTimeout(obj, "读取");

	data = JSON.parse(data);

	$("#sleeptime", $("#sleeptimepopup")).val(data);
	$("#sleeptime", $("#sleeptimepopup")).selectmenu("refresh");
};

/**
 * 设置休眠时间的回调函数
 */
var setSleepTimeCallback = function() {
	var obj = $("#setsleeptimebtn", $("#sleeptimepopup"));
	endTimeout(obj, "设置");
};

/**
 * 显示通信目的指示器设置窗口
 */
var showCommTargetIndicatorWin = function() {

	$("#settargetindicatorbtn", $("#commtargetindicatorpopup")).parent().css(
			"width", "105px");

	// 清空表单
	$("#commtargetindicatorinfo", $("#commtargetindicatorpopup")).hide();
	$("#aphase", $("#commtargetindicatorpopup")).prop("checked", false)
			.checkboxradio("refresh");
	$("#bphase", $("#commtargetindicatorpopup")).prop("checked", false)
			.checkboxradio("refresh");
	$("#cphase", $("#commtargetindicatorpopup")).prop("checked", false)
			.checkboxradio("refresh");
	$(".tipcontentspan", $("#commtargetindicatorpopup")).html("");
	$("#ctindicatoraddr", $("#commtargetindicatorpopup")).html("");

	// 打开对话框
	$("#triggercommtargetindicatorpopup").click();

	// 绑定确定时间
	$("#settargetindicatorbtn", $("#commtargetindicatorpopup")).unbind("click")
			.bind("click", function() {

				var indicatorAddr = $("#ctindicatoraddr",
						$("#commtargetindicatorpopup")).html();

				// 清空提示
				$(".tipcontentspan", $("#commtargetindicatorpopup")).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", $("#commtargetindicatorpopup"))
							.html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				COMM_TARGET_INDICATOR_ADDR = indicatorAddr;
				DEFAULT_IGROUP_ID = null;
				$("#commtargetindicatorpopup").popup("close");
			});
};

/**
 * 显示指示器版本信息窗口
 */
var showIndicatorVerWin = function() {

	var popou = $("#indicatorverpopup");
	$("#readbtn", popou).parent().css("width", "105px");

	$("#info0", popou).hide();
	$("#info", popou).hide();
	$("#aphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#bphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#cphase", popou).prop("checked", false).checkboxradio("refresh");
	$(".tipcontentspan", popou).html("");
	$("#indicatoraddr", popou).html("");
	$("#data", popou).html("");

	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");

	$("#triggerindicatorverpopup").click();
	$("#readbtn", popou).unbind("click").bind("click", function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				// 清空实时电流
				$("#data", popou).html("");

				var indicatorAddr = $("#indicatoraddr", popou).html();

				// 清空提示
				$(".tipcontentspan", popou).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", popou).html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				startTimeout(this, "读取");
				COMM_OPER_TYPE = "getindicatorver";
				try {
					window.debugjsi.getIndicatorVersion(indicatorAddr);
				} catch (e) {
				}
			});
};

/**
 * 获取指示器版本信息的回调方案
 * 
 * @param {}
 *            data
 */
var getIndicatorVersionCallback = function(data) {

	data = JSON.parse(data);
	var info = "硬件: " + data.hardware + "; " + "软件: " + data.software;

	var popou = $("#indicatorverpopup");
	$("#data", popou).html(info);
	$("#label", popou).show();
	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");
};

/**
 * 显示翻牌复归操作窗口
 */
var showIndicatorFlipWin = function() {

	var popou = $("#indicatorflippopup");
	$("#flipbtn", popou).parent().css("width", "105px");
	$("#resetbtn", popou).parent().css("width", "105px");

	$("#info", popou).hide();
	$("#aphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#bphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#cphase", popou).prop("checked", false).checkboxradio("refresh");
	$(".tipcontentspan", popou).html("");
	$("#indicatoraddr", popou).html("");

	var obj = $("#flipbtn", popou);
	endTimeout(obj, "翻牌");

	obj = $("#resetbtn", popou);
	endTimeout(obj, "复归");

	$("#triggerindicatorflippopup").click();
	$("#flipbtn", popou).unbind("click").bind("click", function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				var indicatorAddr = $("#indicatoraddr", popou).html();

				// 清空提示
				$(".tipcontentspan", popou).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", popou).html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				startTimeout(this, "翻牌");
				COMM_OPER_TYPE = "indicatorflip";

				var params = "{'indicatorAddr':'" + indicatorAddr
						+ "','data':'55'}";
				try {
					window.debugjsi.flip(params);
				} catch (e) {
				}
			});

	$("#resetbtn", popou).unbind("click").bind("click", function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				var indicatorAddr = $("#indicatoraddr", popou).html();

				// 清空提示
				$(".tipcontentspan", popou).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", popou).html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				startTimeout(this, "复归");
				COMM_OPER_TYPE = "indicatorflip";

				var params = "{'indicatorAddr':'" + indicatorAddr
						+ "','data':'AA'}";
				try {
					window.debugjsi.flip(params);
				} catch (e) {
				}
			});
};

/**
 * 翻牌回调方法
 * 
 * @param {}
 *            data
 */
var flipCallback = function(data) {

	var popou = $("#indicatorflippopup");

	var type = data.type;
	if ("短路翻牌" == type) {
		var obj = $("#flipbtn", popou);
		endTimeout(obj, "翻牌");
	} else if ("复归" == type) {
		obj = $("#resetbtn", popou);
		endTimeout(obj, "复归");
	}
};

/**
 * 显示指示器实时电场信息窗口
 */
var showIndicatorElecFieldWin = function() {

	var popou = $("#indicatorelecfieldpopup");
	$("#readbtn", popou).parent().css("width", "105px");

	$("#info0", popou).hide();
	$("#info", popou).hide();
	$("#aphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#bphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#cphase", popou).prop("checked", false).checkboxradio("refresh");
	$(".tipcontentspan", popou).html("");
	$("#indicatoraddr", popou).html("");
	$("#data1", popou).html("");
	$("#data2", popou).html("");

	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");

	$("#triggerindicatorelecfieldpopup").click();
	$("#readbtn", popou).unbind("click").bind("click", function() {
				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				// 清空实时电场
				$("#data1", popou).html("");
				$("#data2", popou).html("");

				var indicatorAddr = $("#indicatoraddr", popou).html();

				// 清空提示
				$(".tipcontentspan", popou).html("");
				if (0 >= indicatorAddr.trim().length
						|| "无" == indicatorAddr.trim()) {
					$(".tipcontentspan", popou).html("相位不能为空或相位的指示器地址不能为空!");
					return;
				}

				startTimeout(this, "读取");
				COMM_OPER_TYPE = "getindicatorelecfield";
				try {
					window.debugjsi.getIndicatorElecField(indicatorAddr);
				} catch (e) {
				}
			});
};

/**
 * 获取指示器实时电场信息的回调方案
 * 
 * @param {}
 *            data
 */
var getIndicatorElecFieldCallback = function(data) {

	data = JSON.parse(data);

	var popou = $("#indicatorelecfieldpopup");
	$("#data1", popou).html(data.temp);
	$("#label1", popou).show();
	$("#data2", popou).html(data.average);
	$("#label2", popou).show();
	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");
};

/**
 * 显示指示器模块地址重设窗口
 */
// 原始通信地址和新的通信地址
var ORG_COMM_ADDR;
var NEW_COMM_ADDR;
var showIndicatorCommAddrResetWin = function() {

	var popou = $("#indicatorcommaddrresetpopup");
	$("#resetbtn", popou).parent().css("width", "105px");

	$("#info", popou).hide();
	$("#aphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#bphase", popou).prop("checked", false).checkboxradio("refresh");
	$("#cphase", popou).prop("checked", false).checkboxradio("refresh");
	$(".tipcontentspan", popou).html("");
	$("#indicatoraddr", popou).html("");
	$("#newcommaddr", popou).val("");

	var obj = $("#resetbtn", popou);
	endTimeout(obj, "设置");

	$("#triggerindicatorcommaddrresetpopup").click();
	$("#resetbtn", popou).unbind("click").bind("click", function() {

		if (!USB_ATTACHED) {
			try {
				window.debugjsi.showNoUSBDeviceMsg();
			} catch (e) {
			}
			return;
		}

		var indicatorAddr = $("#indicatoraddr", popou).html();
		ORG_COMM_ADDR = indicatorAddr;

		// 清空提示
		$(".tipcontentspan", popou).html("");
		if (0 >= indicatorAddr.trim().length || "无" == indicatorAddr.trim()) {
			$(".tipcontentspan", popou).html("相位不能为空或相位的指示器地址不能为空!");
			return;
		}

		var newCommAddr = $("#newcommaddr").val();
		NEW_COMM_ADDR = newCommAddr;
		if (null == newCommAddr || undefined == newCommAddr
				|| 6 != newCommAddr.trim().length) {
			$(".tipcontentspan", popou).html("模块新地址错误, 请确认!");
			return;
		}

		startTimeout(this, "设置");
		COMM_OPER_TYPE = "resetindicatorcommaddr";
		try {
			window.debugjsi.resetIndicatorCommAddr(indicatorAddr, newCommAddr);
		} catch (e) {
		}
	});
};

/**
 * 重设指示器无线模块地址的回调方案
 * 
 * @param {}
 *            data
 */
var resetCommAddrCallback = function(data) {

	data = JSON.parse(data);

	var actionReply = data.actionReply;
	if ("OK" == actionReply) {

		// 修改数据库档案
		try {
			window.indicatorjsi.modifyIndicatorAddr(ORG_COMM_ADDR,
					NEW_COMM_ADDR);
		} catch (e) {
		}
	}

	var popou = $("#indicatorcommaddrresetpopup");
	var obj = $("#resetbtn", popou);
	endTimeout(obj, "设置");
};

/**
 * 修改指示器地址的回调方法
 * 
 * @param {}
 *            data
 */
var modifyIndicatorAddrCallback = function(data) {
	var success = data.success;
	if (success) {
		var msg = "重设模块地址成功!";
		showMsg(msg);

		$("#indicator" + data.orgCommAddr).attr("id",
				"indicator" + data.newCommAddr);
	}
};

/**
 * 选择相位
 * 
 * @param {}
 *            phase
 */
var selectPhase = function(phase, func) {
	var cNodes = currObj.childNodes;
	var indicatorAddr = cNodes[parseInt(phase)].id.substring(9);
	indicatorAddr = indicatorAddr.trim().length == 0 ? "无" : indicatorAddr;
	if ("1" == func) {
		$("#rtindicatoraddr", $("#rtcurrentpopup")).html(indicatorAddr);

		$("#rtcurrentinfo", $("#rtcurrentpopup")).show();
		$("#rtcurrentlabel", $("#rtcurrentpopup")).hide();
		$("#rtcurrent", $("#rtcurrentpopup")).html("");
	} else if ("2" == func) {
		$("#stindicatoraddr", $("#sleeptimepopup")).html(indicatorAddr);
		$("#stindicatorinfo", $("#sleeptimepopup")).show();
	} else if ("3" == func) {
		$("#ctindicatoraddr", $("#commtargetindicatorpopup"))
				.html(indicatorAddr);
		$("#commtargetindicatorinfo", $("#commtargetindicatorpopup")).show();
	} else if ("4" == func) {
		var popupObj = $("#indicatorverpopup");
		$("#indicatoraddr", popupObj).html(indicatorAddr);

		$("#info0", popupObj).show();
		$("#info", popupObj).show();
		$("#label", popupObj).hide();
		$("#data", popupObj).html("");
	} else if ("5" == func) {
		var popupObj = $("#indicatorflippopup");
		$("#indicatoraddr", popupObj).html(indicatorAddr);
		$("#info", popupObj).show();
	} else if ("6" == func) {
		var popupObj = $("#indicatorelecfieldpopup");
		$("#indicatoraddr", popupObj).html(indicatorAddr);

		$("#info0", popupObj).show();
		$("#info", popupObj).show();
		$("#label1", popupObj).hide();
		$("#data1", popupObj).html("");
		$("#label2", popupObj).hide();
		$("#data2", popupObj).html("");
	} else if ("7" == func) {
		var popupObj = $("#indicatorcommaddrresetpopup");
		$("#indicatoraddr", popupObj).html(indicatorAddr);
		$("#info", popupObj).show();
	}
}

/**
 * 查询终端版本信息
 */
var getTerminalVersion = function() {

	$("#terminalpopupmenu").popup("close");
	// 查询终端版本信息
	try {
		COMM_OPER_TYPE = "getterminalversion";
		var wirelessAddr = $("#twirelessaddr").val();
		window.debugjsi.getTerminalVersion(wirelessAddr);
	} catch (e) {
	}
};

/**
 * 获取终端版本信息的回调方法
 * 
 * @param {}
 *            data
 */
var getTerminalVersionCallback = function(data) {

	data = JSON.parse(data);
	var info = "<table><tr><td>软件版本</td><td class='info-td'>" + data.swversion
			+ "</td><td>发布日期</td><td class='info-td'>" + data.swdate
			+ "</td></tr>";
	info += "<tr><td>硬件版本</td><td class='info-td'>" + data.hwversion
			+ "</td><td>发布日期</td><td class='info-td'>" + data.hwdate
			+ "</td></tr></table>";

	$("#triggerinfopopup").click();
	var popup = $("#infopopup");
	$("#opermsg", popup).html(info);
};

/**
 * 查询终端通信状态
 */
var getTerminalCommStatus = function() {

	$("#terminalpopupmenu").popup("close");
	// 查询终端版本信息
	try {
		COMM_OPER_TYPE = "getterminalcommstatus";
		var wirelessAddr = $("#twirelessaddr").val();
		window.debugjsi.getTerminalCommStatus(wirelessAddr);
	} catch (e) {
	}
};

/**
 * 获取终端通信状态的回调方法
 * 
 * @param {}
 *            data
 */
var getTerminalCommStatusCallback = function(data) {

	data = JSON.parse(data);
	var regTip = "失败";
	if (Number(data.regstatus) == 1) {
		regTip = "成功";
	}

	var info = "<table><tr><td>注册</td><td class='info-td'>" + regTip
			+ "</td><td>通信阶段</td><td class='info-td'>"
			+ parseInt(data.commstep, 16) + "</td></tr>";
	info += "<tr><td>信号品质</td><td class='info-td'>"
			+ parseInt(data.signalquality, 16)
			+ "</td><td>终端时间</td><td class='info-td'>" + data.currtime
			+ "</td></tr>";
	info += "<tr><td>心跳周期</td><td class='info-td'>" + data.heartbeat
			+ "</td><td>心跳时间</td><td class='info-td'>" + data.lasthearttime
			+ "</td></tr>";
	info += "</table>";

	$("#triggerinfopopup").click();
	var popup = $("#infopopup");
	$("#opermsg", popup).html(info);
};

/**
 * 显示终端地址查设窗口
 */
// 新的终端地址
var NEW_TERMINAL_ADDR;
var showTerminalAddrQRWin = function() {

	var popou = $("#terminaladdrqspopup");
	$("#readbtn", popou).parent().css("width", "105px");
	$("#resetbtn", popou).parent().css("width", "105px");

	$(".tipcontentspan", popou).html("");
	$("#newterminaladdr", popou).val("");
	$("#newterminaladdr").val("");

	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");

	obj = $("#resetbtn", popou);
	endTimeout(obj, "设置");

	$("#triggerterminaladdrqspopup").click();
	$("#readbtn", popou).unbind("click").bind("click", function() {

				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}
				$("#newterminaladdr").val("");
				var wirelessAddr = $("#twirelessaddr").val();

				startTimeout(this, "读取");
				COMM_OPER_TYPE = "getterminaladdr";
				try {
					window.debugjsi.getTerminalAddr(wirelessAddr);
				} catch (e) {
				}
			});

	$("#resetbtn", popou).unbind("click").bind("click", function() {

		if (!USB_ATTACHED) {
			try {
				window.debugjsi.showNoUSBDeviceMsg();
			} catch (e) {
			}
			return;
		}

		var wirelessAddr = $("#twirelessaddr").val();

		// 清空提示
		$(".tipcontentspan", popou).html("");
		var newTerminalAddr = $("#newterminaladdr").val();
		if (null == newTerminalAddr || undefined == newTerminalAddr
				|| 8 != newTerminalAddr.trim().length) {
			$(".tipcontentspan", popou).html("终端地址错误, 请确认!");
			return;
		}

		NEW_TERMINAL_ADDR = newTerminalAddr;

		startTimeout(this, "设置");
		COMM_OPER_TYPE = "setterminaladdr";

		try {
			window.debugjsi.setTerminalAddr(wirelessAddr, newTerminalAddr);
		} catch (e) {
		}
	});
};

/**
 * 读取终端地址的回调方案
 * 
 * @param {}
 *            data
 */
var getTerminalAddrCallback = function(data) {

	data = JSON.parse(data);
	var popou = $("#terminaladdrqspopup");

	$("#newterminaladdr").val(data.terminaladdr.toUpperCase());

	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");
};

/**
 * 重设終端地址的回调方案
 * 
 * @param {}
 *            data
 */
var setTerminalAddrCallback = function() {

	// 修改数据库档案
	try {
		var terminalId = $("#terminalid").val();
		window.terminaljsi.modifyTerminalAddr(terminalId, NEW_TERMINAL_ADDR);
	} catch (e) {
	}

	var popou = $("#terminaladdrqspopup");
	var obj = $("#resetbtn", popou);
	endTimeout(obj, "设置");
};

/**
 * 修改终端地址的回调方法
 * 
 * @param {}
 *            data
 */
var modifyTerminalAddrCallback = function(data) {
	var success = data.success;
	if (success) {
		var msg = "设置终端地址成功!";
		showMsg(msg);

		document.getElementById("TerminalAddr").textContent = data.terminaladdr
				.toUpperCase();
		$("#currterminal").val(data.terminaladdr.toUpperCase());
		$("#terminal_" + $("#terminalid").val()).text(data.terminaladdr
				.toUpperCase());
	}
};

/**
 * 显示终端通信参数查设窗口
 */
var showTerminalCommParamsQSWin = function() {

	var popou = $("#terminalcommparamsqspopup");
	$("#readbtn", popou).parent().css("width", "105px");
	$("#resetbtn", popou).parent().css("width", "105px");

	$(".tipcontentspan", popou).html("");
	$("#newterminaladdr", popou).val("");

	$("#hostip", popou).val("");
	$("#hostport", popou).val("");
	$("#apn", popou).val("");
	$("#heartbeat", popou).val("");
	$("#connection", popou).val("");
	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");

	obj = $("#resetbtn", popou);
	endTimeout(obj, "设置");

	$("#triggerterminalcommparamsqspopup").click();
	$("#readbtn", popou).unbind("click").bind("click", function() {

				if (!USB_ATTACHED) {
					try {
						window.debugjsi.showNoUSBDeviceMsg();
					} catch (e) {
					}
					return;
				}

				$("#hostip", popou).val("");
				$("#hostport", popou).val("");
				$("#apn", popou).val("");
				$("#heartbeat", popou).val("");
				$("#connection", popou).val("");
				var wirelessAddr = $("#twirelessaddr").val();

				startTimeout(this, "读取");
				COMM_OPER_TYPE = "getterminalcommparams";
				try {
					window.debugjsi.getTerminalCommParams(wirelessAddr);
				} catch (e) {
				}
			});

	$("#resetbtn", popou).unbind("click").bind("click", function() {

		if (!USB_ATTACHED) {
			try {
				window.debugjsi.showNoUSBDeviceMsg();
			} catch (e) {
			}
			return;
		}

		var wirelessAddr = $("#twirelessaddr").val();

		// 清空提示
		$(".tipcontentspan", popou).html("");
		var hostIP = $("#hostip", popou).val();
		var hostPort = $("#hostport", popou).val();
		var apn = $("#apn", popou).val();
		var heartBeat = $("#heartbeat", popou).val();
		var connection = $("#connection", popou).val();
		var reg = /^([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/;
		if (null == hostIP || undefined == hostIP || !reg.test(hostIP)) {
			$(".tipcontentspan", popou).html("主站IP地址错误, 请确认!");
			return;
		}

		if (null == hostPort || undefined == hostPort || isNaN(hostPort)) {
			$(".tipcontentspan", popou).html("主站端口错误, 请确认!");
			return;
		}

		if (null == apn || undefined == apn || 0 >= apn.trim().length) {
			$(".tipcontentspan", popou).html("APN不能为空!");
			return;
		}

		if (null == heartBeat || undefined == heartBeat || isNaN(heartBeat)) {
			$(".tipcontentspan", popou).html("心跳周期错误, 请确认!");
			return;
		}

		startTimeout(this, "设置");
		COMM_OPER_TYPE = "setterminalcommparams";
		try {
			window.debugjsi.setTerminalCommParams(wirelessAddr, hostIP,
					hostPort, apn, heartBeat, connection);
		} catch (e) {
		}
	});
};

/**
 * 读取终端通信参数的回调方案
 * 
 * @param {}
 *            data
 */
var getTerminalCommParamsCallback = function(data) {
	data = JSON.parse(data);

	var popou = $("#terminalcommparamsqspopup");
	$("#hostip", popou).val(data.hostip);
	$("#hostport", popou).val(data.hostport);
	$("#apn", popou).val(data.apn);
	$("#heartbeat", popou).val(data.heartbeat);
	$("#connection", popou).val(data.connection).selectmenu("refresh");

	var obj = $("#readbtn", popou);
	endTimeout(obj, "读取");
};

/**
 * 重设終端通信参数的回调方案
 * 
 * @param {}
 *            data
 */
var setTerminalCommParamsCallback = function() {

	var msg = "设置终端通信参数成功!";
	showMsg(msg);

	var popou = $("#terminalcommparamsqspopup");
	var obj = $("#resetbtn", popou);
	endTimeout(obj, "设置");
};

/**
 * 复位终端
 */
var resetTerminal = function() {

	$("#terminalpopupmenu").popup("close");
	try {
		COMM_OPER_TYPE = "resetterminal";
		var wirelessAddr = $("#twirelessaddr").val();
		window.debugjsi.resetTerminal(wirelessAddr);
	} catch (e) {
	}
};

/**
 * 复位终端的回调方法
 * 
 * @param {}
 *            data
 */
var resetTerminalCallback = function() {
	var msg = "复位终端成功!";
	showMsg(msg);
};

/**
 * 更新指示器组的分支级数
 * 
 * @param {}
 *            terminalId
 */
var modifyIGroupBranchLevel = function(terminalId) {
	try {
		var params = "{";
		params += "'terminalid': '" + terminalId + "'";
		params += "}";
		window.indicatorjsi.queryIndicators(params);
	} catch (e) {
	}
};

/**
 * 加载指示器的回调方法
 * 
 * @param {}
 *            data
 */
var loadIndicators = function(data) {
	for (var i = 0; i < data.length; i++) {
		var groupNo = data[i].groupno;
		if (null == groupNo || undefined == groupNo || 0 == groupNo) {
			continue;
		}

		var branch = data[i].branch;
		var level = data[i].level;
		if (null != branch && undefined != branch && 0 != branch
				&& null != level && undefined != level && 0 != level) {
			var node = $("#G" + groupNo, WORK_SVG)[0];
			// 如果存在文本，则先去除
			var textNode = node.childNodes[4];
			if (null != textNode) {
				node.removeChild(textNode);
			}

			var point = getCPoint(node);
			var text = document.createElementNS(svgns, 'text');
			text.setAttribute("x", 2 * RADIUS + 5);
			text.setAttribute("y", RADIUS + 14 / 2);
			text.setAttribute("font-size", 14);
			text.setAttribute("fill", IGROUP_TEXT_COLOR);
			text.textContent = Math.ceil(branch / 3) + " - " + level;
			node.appendChild(text);
		}
	}
}